<template>
  <view class="publish-page">
    <uni-forms ref="formRef" :model="formData" :rules="rules">
      <!-- 商品图片 -->
      <view class="form-section">
        <view class="section-title">
          <text class="title-text">商品图片</text>
          <text class="required">*</text>
        </view>
        <view class="image-upload">
          <view
            v-for="(image, index) in formData.images"
            :key="index"
            class="image-item"
          >
            <image class="uploaded-image" :src="image" mode="aspectFill" />
            <view class="delete-btn" @click="removeImage(index)">
              <uni-icons type="close" color="#FFFFFF" size="16" />
            </view>
          </view>
          <view
            v-if="formData.images.length < 9"
            class="upload-btn"
            @click="chooseImage"
          >
            <uni-icons type="camera" color="#CCCCCC" size="40" />
            <text class="upload-text">添加图片</text>
          </view>
        </view>
        <text class="tip-text">最多可上传9张图片，第一张为封面图</text>
      </view>

      <!-- 商品标题 -->
      <view class="form-section">
        <uni-forms-item name="title" required>
          <view class="section-title">
            <text class="title-text">商品标题</text>
            <text class="required">*</text>
          </view>
          <uni-easyinput
            v-model="formData.title"
            placeholder="请输入商品标题"
            maxlength="50"
          />
        </uni-forms-item>
      </view>

      <!-- 商品分类 -->
      <view class="form-section">
        <uni-forms-item name="categoryId" required>
          <view class="section-title">
            <text class="title-text">商品分类</text>
            <text class="required">*</text>
          </view>
          <uni-data-select
            v-model="formData.categoryId"
            :localdata="categories"
            placeholder="请选择商品分类"
          />
        </uni-forms-item>
      </view>

      <!-- 商品价格 -->
      <view class="form-section">
        <uni-forms-item name="price" required>
          <view class="section-title">
            <text class="title-text">商品价格</text>
            <text class="required">*</text>
          </view>
          <view class="price-input">
            <text class="currency">¥</text>
            <uni-easyinput
              v-model="formData.price"
              type="number"
              placeholder="0.00"
              :inputBorder="false"
            />
          </view>
        </uni-forms-item>
      </view>

      <!-- 原价（可选） -->
      <view class="form-section">
        <view class="section-title">
          <text class="title-text">原价</text>
          <text class="optional">（选填）</text>
        </view>
        <view class="price-input">
          <text class="currency">¥</text>
          <uni-easyinput
            v-model="formData.originalPrice"
            type="number"
            placeholder="0.00"
            :inputBorder="false"
          />
        </view>
      </view>

      <!-- 商品描述 -->
      <view class="form-section">
        <uni-forms-item name="description" required>
          <view class="section-title">
            <text class="title-text">商品描述</text>
            <text class="required">*</text>
          </view>
          <uni-easyinput
            v-model="formData.description"
            type="textarea"
            placeholder="请详细描述商品的品牌、型号、新旧程度、使用情况等"
            maxlength="500"
            :autoHeight="true"
          />
        </uni-forms-item>
      </view>

      <!-- 联系方式 -->
      <view class="form-section">
        <view class="section-title">
          <text class="title-text">联系方式</text>
        </view>
        <view class="contact-options">
          <uni-data-checkbox
            v-model="formData.contactMethods"
            :localdata="contactOptions"
            multiple
          />
        </view>
      </view>
    </uni-forms>

    <!-- 底部按钮 -->
    <view class="bottom-actions">
      <button class="preview-btn" @click="previewGoods">预览</button>
      <button class="publish-btn" @click="submitForm" :loading="publishing">
        发布
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { publishGoods } from "../../api/goods";
import type { GoodsItem } from "../../types/goods";

// 表单引用
const formRef = ref();

// 表单数据
const formData = reactive({
  title: "",
  description: "",
  price: "",
  originalPrice: "",
  images: [] as string[],
  categoryId: "",
  contactMethods: [] as string[],
});

// 表单验证规则
const rules = {
  title: {
    rules: [
      { required: true, errorMessage: "请输入商品标题" },
      {
        minLength: 5,
        maxLength: 50,
        errorMessage: "标题长度应在5-50个字符之间",
      },
    ],
  },
  categoryId: {
    rules: [{ required: true, errorMessage: "请选择商品分类" }],
  },
  price: {
    rules: [
      { required: true, errorMessage: "请输入商品价格" },
      { pattern: /^\d+(\.\d{1,2})?$/, errorMessage: "请输入正确的价格格式" },
    ],
  },
  description: {
    rules: [
      { required: true, errorMessage: "请输入商品描述" },
      {
        minLength: 10,
        maxLength: 500,
        errorMessage: "描述长度应在10-500个字符之间",
      },
    ],
  },
};

// 商品分类选项
const categories = [
  { value: "1", text: "服装" },
  { value: "2", text: "书籍" },
  { value: "3", text: "数码" },
  { value: "4", text: "家居" },
  { value: "5", text: "运动" },
  { value: "6", text: "美妆" },
  { value: "7", text: "母婴" },
  { value: "8", text: "其他" },
];

// 联系方式选项
const contactOptions = [
  { value: "wechat", text: "微信" },
  { value: "phone", text: "电话" },
  { value: "message", text: "站内消息" },
];

// 发布状态
const publishing = ref(false);

// 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 9 - formData.images.length,
    sizeType: ["compressed"],
    sourceType: ["album", "camera"],
    success: (res: any) => {
      formData.images.push(...res.tempFilePaths);
    },
    fail: (error: any) => {
      console.error("选择图片失败:", error);
      uni.showToast({
        title: "选择图片失败",
        icon: "none",
      });
    },
  });
};

// 删除图片
const removeImage = (index: number) => {
  formData.images.splice(index, 1);
};

// 预览商品
const previewGoods = () => {
  if (formData.images.length === 0) {
    uni.showToast({
      title: "请先添加商品图片",
      icon: "none",
    });
    return;
  }

  // TODO: 实现预览功能
  uni.showToast({
    title: "预览功能开发中",
    icon: "none",
  });
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  // 验证图片
  if (formData.images.length === 0) {
    uni.showToast({
      title: "请至少添加一张商品图片",
      icon: "none",
    });
    return;
  }

  // 表单验证
  try {
    await formRef.value.validate();
  } catch (error) {
    console.log("表单验证失败:", error);
    return;
  }

  publishing.value = true;

  try {
    // TODO: 上传图片并获取URL
    // const imageUrls = await uploadImages(formData.images)

    // TODO: 调用发布API
    // const response = await publishGoods({
    // 	title: formData.title,
    // 	description: formData.description,
    // 	price: parseFloat(formData.price),
    // 	originalPrice: formData.originalPrice ? parseFloat(formData.originalPrice) : undefined,
    // 	images: imageUrls,
    // 	categoryId: formData.categoryId
    // })

    // 模拟发布成功
    await new Promise((resolve) => setTimeout(resolve, 2000));

    uni.showToast({
      title: "发布成功",
      icon: "success",
    });

    // 返回首页
    setTimeout(() => {
      uni.switchTab({
        url: "/pages/index/index",
      });
    }, 1500);
  } catch (error) {
    console.error("发布失败:", error);
    uni.showToast({
      title: "发布失败，请重试",
      icon: "none",
    });
  } finally {
    publishing.value = false;
  }
};
</script>

<style lang="scss" scoped>
.publish-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.form-section {
  background-color: #ffffff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.title-text {
  font-size: 32rpx;
  color: #333333;
  font-weight: 500;
}

.required {
  color: #ff4444;
  margin-left: 5rpx;
}

.optional {
  color: #999999;
  margin-left: 5rpx;
  font-size: 24rpx;
}

.image-upload {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.image-item {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.uploaded-image {
  width: 100%;
  height: 100%;
}

.delete-btn {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-btn {
  width: 200rpx;
  height: 200rpx;
  border: 2rpx dashed #cccccc;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
}

.upload-text {
  font-size: 24rpx;
  color: #cccccc;
  margin-top: 10rpx;
}

.tip-text {
  font-size: 24rpx;
  color: #999999;
  margin-top: 20rpx;
  display: block;
}

.price-input {
  display: flex;
  align-items: center;
  border: 1rpx solid #eeeeee;
  border-radius: 8rpx;
  padding: 0 20rpx;
  background-color: #fafafa;
}

.currency {
  font-size: 32rpx;
  color: #333333;
  margin-right: 10rpx;
}

.contact-options {
  margin-top: 20rpx;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  background-color: #ffffff;
  border-top: 1rpx solid #eeeeee;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  gap: 20rpx;
}

.preview-btn {
  flex: 1;
  height: 80rpx;
  background-color: #ffffff;
  color: #07c160;
  border: 2rpx solid #07c160;
  font-size: 32rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.publish-btn {
  flex: 2;
  height: 80rpx;
  background-color: #07c160;
  color: #ffffff;
  font-size: 32rpx;
  font-weight: bold;
  border-radius: 40rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
